package com.fast.cron.db.service;

import com.fast.cron.db.dao.AbstractDao;
import com.fast.cron.db.dao.ExecutionJobDao;
import com.fast.cron.db.entry.ExecutionJob;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

/**
 * @author: Leo Jie
 * @date: 2018-10-04 20:40
 * @version: v1.0
 */
public class ExecutionJobService extends AbstractDao implements ExecutionJobDao {
    @Override
    public long saveExecutionJob(ExecutionJob executionJob) throws SQLException {
        String sql = "insert fast_cron_execution_job(job_id,schedule_job_id, execution_way, `start`)\n" +
                "    values (?,?,?,?);";
        return insert(sql, executionJob.getJobId(), executionJob.getScheduleJobId(), executionJob.getExecutionWay(),
                executionJob.getStart());
    }

    @Override
    public int refreshEndTimeOfExecutionJob(int executionJobId, Timestamp endTime) throws SQLException {
        String sql = "update fast_cron_execution_job set `end` = ? where id= ?;";
        return update(sql, endTime, executionJobId);
    }

    @Override
    public int refreshRunTimesOfExecutionJob(int executionJobId, int executionTimes) throws SQLException {
        String sql = "update fast_cron_execution_job set execution_times = ? where id= ?;";
        return update(sql, executionTimes, executionJobId);
    }

    @Override
    public int refreshStatusOfExecutionJob(int executionJobId, int executionStatus) throws SQLException {
        String sql = "update fast_cron_execution_job set execution_status = ? where id= ?;";
        return update(sql, executionStatus, executionJobId);
    }

    @Override
    public List<Map<String, Object>> listJobsOfExecution() throws SQLException {
        String sql = "select\n" +
                "  fast_cron_execution_job.id,\n" +
                "  fast_cron_execution_job.job_id,\n" +
                "  fast_cron_execution_job.schedule_job_id,\n" +
                "  fast_cron_job.job_name,\n" +
                "  fast_cron_job.job_detail,\n" +
                "  fast_cron_job.job_command,\n" +
                "  fast_cron_execution_job.execution_way,\n" +
                "  fast_cron_execution_job.`start`,\n" +
                "  fast_cron_execution_job.`end`,\n" +
                "  fast_cron_execution_job.execution_times,\n" +
                "  fast_cron_execution_job.execution_status\n" +
                "from fast_cron_execution_job\n" +
                "  left join fast_cron_job\n" +
                "    on fast_cron_execution_job.job_id = fast_cron_job.job_id\n" +
                "order by fast_cron_execution_job.`start` asc;";
        return query(sql);
    }
}